package com.cyzy.server.controller.admin;

import com.cyzy.common.constant.JwtClaimsConstant;
import com.cyzy.common.constant.MessageConstant;
import com.cyzy.common.properties.JwtProperties;
import com.cyzy.common.result.Result;
import com.cyzy.common.utils.JwtUtil;
import com.cyzy.pojo.dto.SuperintendentDTO;
import com.cyzy.pojo.dto.SuperintendentLoginDTO;
import com.cyzy.pojo.entity.Superintendent;
import com.cyzy.pojo.vo.SuperintendentLoginVO;
import com.cyzy.server.service.SuperintendentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin/superintendent")
@Slf4j
public class SuperintendentController {
    @Autowired
    private SuperintendentService superintendentService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 注册
     */
    @PostMapping("/register")
    public Result<SuperintendentLoginVO> register(@RequestBody SuperintendentDTO superintendentDTO) {
        log.info("管理者注册：", superintendentDTO);

        superintendentService.register(superintendentDTO);
        String msg = "管理员注册成功！";
        return Result.success(msg);

    }

    /**
     * 管理者登录
     */
    @PostMapping("/login")
    public Result<SuperintendentLoginVO> login(@RequestBody SuperintendentLoginDTO superintendentLoginDTO) {
        log.info("管理者登录：{}", superintendentLoginDTO);

        Superintendent superintendent = superintendentService.login(superintendentLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.STUDENT_ID, superintendent.getStudentId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        SuperintendentLoginVO superintendentLoginVO = SuperintendentLoginVO.builder()
                .id(superintendent.getId())
                .userName(superintendent.getName())
                .token(token)
                .build();

        //登录成功返回登录成功信息
        String msg = MessageConstant.LOGIN_SUCCESS;

        return Result.success(superintendentLoginVO, msg);
    }


}
